package com.zyj.dynds.component;

import com.zyj.dynds.consts.DataSourceKey;

/**
 * 使用 ThreadLocal 保存当前线程所使用的 DataSourceKey
 */
public class DynamicDataSourceHolder {

    private static ThreadLocal<DataSourceKey> contextHolder = new ThreadLocal<DataSourceKey>(){
        @Override
        public DataSourceKey initialValue(){
            return DB_MASTER;
        }
    };

    public static final DataSourceKey DB_MASTER = DataSourceKey.master;
    public static final DataSourceKey DB_SLAVE = DataSourceKey.slave;

    /**
     * 获取dbType
     *
     * @return DataSourceKey
     */
    public static DataSourceKey getDataSourceKey() {
        return contextHolder.get();
    }

    /**
     * 设置线程的dbType
     *
     * @param dataSourceKey
     */
    public static void setDataSourceKey(DataSourceKey dataSourceKey) {
        contextHolder.set(dataSourceKey);
    }

    /**
     * 清理连接类型
     */
    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

}
